<template>
  <div class="order_list">
    <van-tabs
      v-model="activeIndex"
      line-width="0"
      title-active-color="#EE3F00"
      title-inactive-color="#111111"
      background="#F8F8F8"
      :swipe-threshold="5"
      @click="handleTabClick"
    >
      <van-tab
        v-for="(tabTitle, index) in tabTitles"
        :title="tabTitle"
        :key="index"
      >
        <van-list
          v-model="loading"
          :finished="finished"
          :immediate-check="false"
          finished-text="没有更多了"
          @load="getOrderList"
        >
          <van-panel
            v-for="(el, i) in orderList"
            :key="i"
            :title="'订单编号: ' + el.orderSn"
            :status="el.orderStatusText"
            @click.native="toOrderDetail(el.id)"
          >
            <div
              slot="header"
              style="
                position: relative;
                padding: 8px 16px 16px 16px;
                font-size: 11px;
              "
            >
              订单编号:{{ el.orderSn }}

              <br />
              <span
                style="
                  position: absolute;
                  top: 27px;
                  right: 16px;
                  color: #7d7e80;
                  font-size: 9px;
                "
                v-show="el.orderStatusText == '订单取消，退款中'"
                >3个工作日内原路退回</span
              >
            </div>

            <div
              class="van-card"
              v-for="(goods, goodsI) in el.goodsList"
              :key="goodsI"
            >
              <div class="van-card__header">
                <a class="van-card__thumb">
                  <div class="van-image" style="width: 100%; height: 100%">
                    <img
                      :src="goods.picUrl"
                      class="van-image__img"
                      style="object-fit: cover"
                    />
                  </div>
                </a>
                <div
                  class="van-card__content"
                  style="justify-content: space-between"
                >
                  <div>
                    <div
                      class="van-card__title van-multi-ellipsis--l2"
                      style="display: flex; justify-content: space-between"
                    >
                      <div>{{ goods.goodsName }}</div>
                      <div class="van-card__num">x{{ goods.number }}</div>
                    </div>
                    <div>
                      <div class="desc">
                        <span
                          v-for="(spec, index) in goods.specifications"
                          :key="index"
                          class="
                            van-tag van-tag--plain van-tag--default
                            van-hairline--surround
                          "
                          style="margin-right: 6px"
                          >{{ el.orderType == 0 ? spec : getSpec(el) }}</span
                        >
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div
                style="display: flex; padding-left: 98px; margin-top: 5px"
                v-if="
                  goods.giftGoods !== undefined && goods.giftGoods.length > 0
                "
              >
                <span
                  style="
                    font-weight: bold;
                    color: #000;
                    float: left;
                    font-size: 11px;
                  "
                  >赠品</span
                >
                <div
                  style="
                    margin-left: 6px;
                    display: flex;
                    flex-direction: column;
                    font-size: 11px;
                    width: calc(100% - 30px);
                  "
                >
                  <div
                    style="width: 100%; line-height: 16px"
                    v-for="(gift, index) in goods.giftGoods"
                    :key="index"
                  >
                    <span
                      style="
                        width: calc(100% - 18px);
                        float: left;
                        display: inline-block;
                        text-align: left;
                        display: inline-block;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                      "
                    >
                      {{ gift.giftName }}</span
                    ><span style="float: right; margin-left: 5px"
                      >*{{ gift.num * goods.number }}</span
                    >
                  </div>
                </div>
              </div>
            </div>
            <div class="total">合计: {{ (el.actualPrice * 100) | yuan }}</div>

            <div slot="footer" class="footer_btn" style="height: 32px">
              <span
                style="color: #db3d3c; position: absolute; top: 8px; left: 16px"
                >{{ el.orderStatusText }}</span
              >
              <van-button
                size="small"
                v-if="el.payType == 1 && el.handleOption.refund"
                type="danger"
                @click.stop="toPayGoods(el.id, el.payWay, 2)"
                >付定金</van-button
              >
              <van-button
                size="small"
                v-if="
                  (el.payType == 1 || el.payType == 2) && el.handleOption.refund
                "
                type="danger"
                @click.stop="toPayGoods(el.id, el.payWay, 3)"
                >付尾款</van-button
              >
              <van-button
                size="small"
                v-if="el.handleOption.cancel"
                @click.stop="cancelOrder(el.id)"
                >取消订单</van-button
              >
              <van-button
                size="small"
                v-if="el.handleOption.pay"
                type="danger"
                @click.stop="toPayGoods(el.id, el.payWay, el.payType)"
                >去支付</van-button
              >
              <van-button
                size="small"
                v-if="el.handleOption.refund && el.payType != 1"
                @click.stop="
                  remindTheDelivery(
                    el.id,
                    el.orderSn,
                    el.orderStatusText,
                    el.actualPrice
                  )
                "
                >提醒发货</van-button
              >
              <!-- <van-button size="small"
                          v-if="el.handleOption.refund"
                          type="danger"
              @click.stop="refundOrder(el.id)">退款</van-button>-->
              <van-button size="small" v-if="el.handleOption.confirm"
                >查看物流</van-button
              >
              <van-button
                size="small"
                v-if="el.handleOption.confirm"
                type="danger"
                @click.stop="confirmOrder(el.id)"
                >确认收货</van-button
              >
              <van-button
                size="small"
                v-if="el.handleOption.delete"
                @click.stop="delOrder(el.id)"
                >删除订单</van-button
              >
              <van-button
                style="display: none"
                size="small"
                v-if="el.handleOption.comment"
                @click.stop="commentOrder(el.id)"
                >去评价</van-button
              >
            </div>
          </van-panel>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import {
  orderList,
  orderDelete,
  orderConfirm,
  orderCancel,
  orderRefund,
  remindDelivery,
} from '@/api/api';
import _ from 'lodash';
import { Tab, Tabs, Panel, Card, List, Tag, Dialog } from 'vant';
import {
  getLocalStorage,
  setLocalStorage,
  removeLocalStorage,
} from '@/utils/local-storage';

export default {
  name: 'order-list',

  props: {
    active: {
      type: [String, Number],
      default: 0,
    },
  },
  created() {
    this.init();
  },
  data() {
    return {
      activeIndex: Number(this.active),
      tabTitles: ['全部', '待付款', '待发货', '待收货', '已完成'],
      //tabTitles: ['全部', '待付款', '已完成'],
      orderList: [],
      page: 0,
      limit: 10,
      loading: false,
      finished: false,
    };
  },

  methods: {
    getSpec(el) {
      if (el.payType == 1) {
        return '试机';
      } else if (el.payType == 2) {
        return '定金';
      } else if (el.payType == 3) {
        return '全款';
      }
    },
    init() {
      this.page = 0;
      this.orderList = [];
      this.getOrderList();
    },
    getOrderList() {
      this.page++;
      orderList({
        showType: this.activeIndex,
        page: this.page,
        limit: this.limit,
      }).then((res) => {
        this.orderList.push(...res.data.data.list);
        //console.log(JSON.stringify(this.orderList));
        this.loading = false;
        this.finished = res.data.data.page >= res.data.data.pages;
      });
    },
    delOrder(id) {
      let that = this;
      this.$dialog
        .confirm({ message: '确定要删除该订单吗?' })
        .then(() => {
          orderDelete({ orderId: id }).then(() => {
            this.init();
            this.$toast('已删除订单');
          });
        })
        .catch(() => {});
    },
    cancelOrder(id) {
      this.$dialog
        .confirm({ message: '确定要取消该订单吗?' })
        .then(() => {
          orderCancel({ orderId: id }).then(() => {
            this.init();
            this.$toast('已取消该订单');
          });
        })
        .catch(() => {});
    },
    refundOrder(id) {
      this.$dialog
        .confirm({ message: '确定要申请退款吗?' })
        .then(() => {
          orderRefund({ orderId: id }).then(() => {
            this.init();
            this.$toast('已申请订单退款');
          });
        })
        .catch(() => {});
    },
    remindTheDelivery(id, orderNo, orderStatus, actualPrice) {
      let infoData = getLocalStorage('remindData');
      infoData.remindData = JSON.parse(infoData.remindData);
      if (
        infoData.remindData != null &&
        infoData.remindData.remindTime != this.getToday()
      ) {
        removeLocalStorage('remindData');
        infoData = getLocalStorage('remindData');
      }

      if (
        infoData.remindData != null &&
        infoData.remindData.remindTime == this.getToday() &&
        infoData.remindData.ids.indexOf(',' + id + ',') != -1
      ) {
        this.$dialog.alert({ message: '今日已经提醒发货，请勿重复提醒！' });
        return;
      }
      let sotrageIds = ',';
      if (infoData.remindData != null) {
        sotrageIds = infoData.remindData.ids;
      }

      this.$dialog.confirm({ message: '确定要提醒发货吗?' }).then(() => {
        remindDelivery({
          orderId: id,
          orderNo: orderNo,
          orderStatus: orderStatus,
          orderMoney: actualPrice,
        })
          .then((res) => {
            this.$toast('已提醒发货！');
            let remindObject = {};
            this.$set(remindObject, 'remindTime', this.getToday());
            this.$set(remindObject, 'ids', sotrageIds + id + ',');
            setLocalStorage({ remindData: JSON.stringify(remindObject) });
          })
          .catch((err) => {
            this.$toast('找不到对应客户经理，请联系管理员！');
          });
      });
    },
    getToday() {
      var now = new Date();
      var year = now.getFullYear(); //年
      var month = now.getMonth() + 1; //月
      var day = now.getDate(); //日
      var clock = year + '-';
      if (month < 10) clock += '0';
      clock += month + '-';
      if (day < 10) clock += '0';
      clock += day + ' ';
      return clock;
    },
    confirmOrder(id) {
      this.$dialog
        .confirm({
          message: '请确认收到货物, 确认收货后无法撤销!',
        })
        .then(() => {
          orderConfirm({ orderId: id }).then(() => {
            this.init();
            this.$toast('已确认收货');
          });
        })
        .catch(() => {});
    },
    commentOrder(id) {},
    toPayGoods(id, payWay, payType, el) {
      // console.log('goodsId = ' + goodsId);
      if (payWay == 1) {
        Dialog.alert({
          message:
            '您已选择线下支付，您的客户经理将会协助您完成线下支付，感谢您对喷喷涂涂的信任。',
        }).then(() => {});
        return;
      }
      // payType 0：全款 1：试机 2：定金 3：尾款
      if (el && (el.mmodular == 1 || el.modular == 1)) {
        //原料订单支付页面
        this.$router.push({
          name: 'rawPayment',
          query: {
            orderId: id,
            payType: 0,
          },
        });
      } else {
        this.$router.push({
          name: 'payment',
          query: {
            orderId: id,
            payType: payType,
          },
        });
      }
    },
    handleTabClick() {
      this.page = 0;
      this.orderList = [];
      this.getOrderList();
    },
    toOrderDetail(id) {
      this.$router.push({
        path: '/order/order-detail',
        query: { orderId: id },
      });
    },
  },
  components: {
    [Dialog.name]: Dialog,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Panel.name]: Panel,
    [Card.name]: Card,
    [List.name]: List,
    [Tag.name]: Tag,
  },
};
</script>

<style lang="scss" scoped>
/deep/ .van-tabs__nav--line {
  position: fixed;
  z-index: 100;
  padding-bottom: 0;
  height: 44px;
  width: 100%;
}

.van-tabs__nav {
  margin: 0;
}
.order_list {
  .van-panel {
    margin-top: 20px;
  }

  .van-card:not(:first-child) {
    margin-top: 5px;
    padding: 8px 16px;
  }

  .van-card {
    padding: 0 16px 8px 16px;
    background-color: #fff;
  }

  .total {
    text-align: right;
    padding: 10px;
  }

  .footer_btn {
    text-align: right;
    .van-button {
      margin-left: 10px;
    }
  }
}
</style>
